<!--
 * @Date: 2024-10-24 11:29:19
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-11-19 10:55:05
 * @Description: 
-->
<template>
  <rk-dialog width="85%"
    height="80%"
    title='评分标准配置'
    :visible="localVisible"
    :destroyOnClose="true"
    @close="localVisible = false"
    :maskClosable="false">
    <template #footer>
      <el-button @click="saveExpertRuleClick"
        type="primary">保存</el-button>
      <el-button @click="localVisible=false">取消</el-button>
    </template>
    <el-form class="rk-form">
      <el-row class="mb20">
        <el-col :span="12">
          <el-form-item label="所属区划"
            label-width="100"
            :rules="{required:true}">
            <el-input disabled
              :model-value="row.adName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态"
            label-width="100"
            :rules="{required:true}">
            <el-select disabled
              :model-value="row.status">
              <el-option label="启用"
                value="1"></el-option>
              <el-option label="停用"
                value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mb20">
        <el-col :span="12">
          <el-form-item label="专家名称"
            label-width="100"
            :rules="{required:true}">
            <el-input disabled
              :model-value="row.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号码"
            label-width="100"
            :rules="{required:true}">
            <el-input disabled
              :model-value="row.idCard"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mb20">
        <el-col :span="12">
          <el-form-item label="联系方式"
            label-width="100"
            :rules="{required:true}">
            <el-input disabled
              :model-value="row.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮件"
            label-width="100">
            <el-input disabled
              :model-value="row.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <rk-grid ref="expertRuleManageRef"
      title="专家规则维护"
      :data="currentExpertData"
      height="75%"
      box-config
      :toolbarConfig="{ zoom: false, refresh: false}"
      :seq-config="false"
      :pager-config="false"
      :columns="ruleColumns">
      <template #toolbar_right>
        <el-button type="primary"
          @click="localpfAddClick">增加
        </el-button>
        <el-button @click="deleteExpertRuleClick"
          type="danger">删除</el-button>
      </template>
    </rk-grid>

  </rk-dialog>
  <rk-dialog width="80%"
    height="70%"
    :top="0"
    title='选择评分标准'
    :visible="localpfVisible"
    :destroyOnClose="true"
    @close="localpfVisible = false"
    :maskClosable="false">
    <template #footer>
      <el-button type="primary"
        @click="addRulePFClick">确认
      </el-button>
      <el-button @click="localpfVisible=false">取消</el-button>
    </template>
    <rk-grid ref="scoingRef"
      boxConfig
      keyField="pfbzId"
      :data="scoinDataList"
      :columns="ruleColumns"
      :loading="pfLoading"
      :pager-config="false"
      :checkboxConfig="{ reserve: true}">
      <template #toolbar_right>
        <rk-tree-select enum="EXPERT_SCORE_STATUS"
          :filterable="false"
          :showCode="false"
          :clearable="true"
          v-model="notAssignQueryParams.scoreType"
          @change="handlerScoreSearch">
        </rk-tree-select>
      </template>
    </rk-grid>

  </rk-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { defAxios as request } from '@/utils/http'

const props = defineProps({
  ok: {
    type: [Promise, Function],
    default: () => {
      return new Promise(resolve => resolve())
    }
  },
  cancel: {
    type: Promise,
    default: () => {
      return new Promise(resolve => resolve())
    }
  },
  // 类型
  type: { type: String, default: 'rule' },
  // 是否可见
  visible: { type: Boolean, default: false },
  // 额外参数
  extParams: { type: Object, default: () => ({})},
  // 取消方法
  onCancel: { type: Function },
  // 确认方法
  onConfirm: { type: Function },
  // 销毁方法
  onDestory: { type: Function },
})


const notAssignQueryParams = reactive({
  scoreType: '',
  expertId: '',
  delRuleIds: ''
})

const ruleColumns = ref([
  {
    field: 'entryLev1',
    title: '一级条目',
    width: 250,
    align: 'left',
  },
  { field: 'entryLev2', title: '二级条目', width: 200, align: 'left', },
  { field: 'reviewDesc', title: '评审内容', width: 550, align: 'left', },
  { field: 'reviewStandard', title: '评审标准', width: 220, align: 'left', },
  {
    field: 'scoreType',
    title: '评分选项',
    width: 120,
    align: 'center',
    formatter: ({ cellValue }) => {
      return cellValue == 1 ? '分数' : '是/否'
    }
  },
  {
    field: 'scoreRange', title: '分值', width: 200, align: 'center',
    formatter: ({ cellValue, row }) => {
      return row.scoreType == 1 ? cellValue : '--'
    }
  },
  {
    field: 'remark', title: '备注', width: 100, align: 'left'
  },
])
const currentExpertData = ref([])
const localVisible = ref(props.visible)
const localpfVisible = ref(false)

const pfLoading = ref(false)

const expertRuleManageRef = ref(null)
const scoingRef = ref(null)
const row = ref({})
const scoinDataList = ref([])


const saveExpertRuleClick = () => {
  let pfbzIds = currentExpertData.value.map(item => {
    return item.pfbzId
  })
  if (!pfbzIds) {
    pfbzIds = [""]
  }
  request({
    url: `/expert/saveRule`,
    method: 'post',
    data: { expertId: row.value.expertId, ruleIds: pfbzIds.join(",") }
  }).then(resp => {
    if (resp.code === 200) {
      localVisible.value = false
      ElMessage.success("评审规则保存成功！")
      handleConfirm()
      return
    }
    ElMessage.success("评审规则保存失败！")
  })
}

const handleConfirm = async() => {
  if (props.onConfirm) { props.onConfirm(result) }
  handleDestory()
}
const handleDestory = () => {
  if (props.onDestory) { props.onDestory() }
}

const deleteExpertRuleClick = () => {
  let seleRows = expertRuleManageRef.value.getCheckboxRecords();
  if (!seleRows || seleRows.length === 0) {
    ElMessage.warning({ message: `请至少选择一条数据进行删除！` })
    return
  }
  let deleteIds = seleRows.map(item => {
    return item.pfbzId
  })
  notAssignQueryParams.delRuleIds = deleteIds.join(",")
  currentExpertData.value = currentExpertData.value.filter(val => {
    return !deleteIds.includes(val.pfbzId)
  })
}

const handlerScoreSearch = (data) => {
  pfLoading.value = true
  notAssignQueryParams.scoreType = data || ""
  notAssignQueryParams.expertId = row.value.expertId
  request({
    url: `/expert/notAssignRuleList`,
    method: 'post',
    data: notAssignQueryParams
  }).then((resp) => {
    if (resp.code === 200) {
      if (resp.data) {

        if (currentExpertData.value) {
          let exists = currentExpertData.value.map(item => {
            return item.pfbzId
          })
          scoinDataList.value = resp.data.filter(item => {
            return !exists.includes(item.pfbzId)
          })
        } else {
          scoinDataList.value = resp.data
        }
      }
    }
    pfLoading.value = false
  })
}
const addRulePFClick = () => {
  let seleRows = scoingRef.value.getCheckboxRecords();
  if (!seleRows || seleRows.length === 0) {
    ElMessage.warning({ message: `请至少选择一条数据进行添加！` })
    return
  }
  if (notAssignQueryParams.delRuleIds) {
    let delRuleIds = notAssignQueryParams.delRuleIds.split(",")
    seleRows.filter(item => {
      return delRuleIds.includes(item.pfbzId)
    }).forEach(v => {
      let index = delRuleIds.indexOf(v.pfbzId)
      delRuleIds.splice(index, 1)
    })
    notAssignQueryParams.delRuleIds = delRuleIds.join(",")
  }

  currentExpertData.value = sortExpertData(seleRows)
  localpfVisible.value = false
}
const sortExpertData = (rows) => {
  let tempRule = []
  let resultRule = []
  if (currentExpertData.value) {
    tempRule = currentExpertData.value.map(item => {
      return item
    })
  }
  tempRule.push(...rows)
  let temp = {}
  tempRule.forEach(item => {
    if (!temp.hasOwnProperty(item.scoreType)) {
      temp[item.scoreType] = []
    }
    temp[item.scoreType].push(item)
  })
  for (let key in temp) {
    temp[key] = temp[key].sort((v1, v2) => {
      return v1.pfbzOrder - v2.pfbzOrder
    })
  }
  if (temp.hasOwnProperty("2")) {
    resultRule.push(...temp["2"])
  }
  if (temp.hasOwnProperty("1")) {
    resultRule.push(...temp["1"])
  }
  return resultRule
}
const handleOpen = (data) => {
  row.value = data
  notAssignQueryParams.delRuleIds = ""
  request({
    url: `/expert/assignRuleList/${row.value.expertId}`,
    method: 'get',
  }).then(resp => {
    if (resp.code === 200) {
      currentExpertData.value = resp.data || []
    }
  })
  // localVisible.value = true
}
const handleClose = () => {
  localVisible.value = false
}

const localpfAddClick = () => {
  localpfVisible.value = true
  handlerScoreSearch()
}

handleOpen(props.extParams.data)

defineExpose({
  handleClose,
  handleOpen
})


</script>

<style scoped lang="scss">
</style>
